package org.jsping.music;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsping.entity.Music;
import org.jsping.util.AuthUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 爬取音乐的murl,lyric,img的相关信息
 */
public class NewMusic {
	// 存储一次获取的歌曲k==歌曲的mname，v==歌曲
	private Map<String, Music> musicMap = new HashMap<String, Music>();

	public Map<String, Music> getMusicMap() {
		return musicMap;
	}
	public void setMusicMap(Map<String, Music> musicMap) {
		this.musicMap = musicMap;
	}

	// 先获取歌曲名称，歌曲演唱歌手名称
	public void setMusic(String mname) {
		String url = "https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?is_xml=0&format=jsonp&key=" + mname
				+ "&outCharset=utf-8&jsonpCallback=SmartboxKeys";
		String json = null;
		try {
			json = AuthUtil.doGetMusic(url);
		} catch (IOException e) {
			e.printStackTrace();
		}

		json = json.replace("SmartboxKeys(", "");
		// 获取纯json
		json = json.substring(0, json.length() - 1);
		// 把json字符串解析成json对象
		JSONObject jobj = JSON.parseObject(json);
		// 解析data
		JSONObject jdata = jobj.getJSONObject("data");
		
		// 解析获得song节点
		JSONObject song = jdata.getJSONObject("song");
		//防止没有歌曲就去爬，防止null
		if(song==null) {
			return;
		}
		// 获取每个歌曲的选项
		// 获取每个歌曲的json字符串
		JSONArray itemlist = song.getJSONArray("itemlist");
		// 解析每个歌曲
		for (int i = 0; i < itemlist.size(); i++) {
			JSONObject item = itemlist.getJSONObject(i);
			// 每首歌曲
			Music m = new Music();
			System.out.println("歌手：" + item.getString("singer") + "\t歌曲名：" + item.getString("name") + "\tmid:"
					+ item.getString("mid"));
			// 歌曲名
			m.setMname(item.getString("name"));
			// 歌手名
			m.setSname(item.getString("singer"));
			musicMap.put(item.getString("mid"), m);
		}
	}

	// 获取歌曲的真实URL
	public void setMusicInfo() {
		// 请求vkey
		String vkurl = "https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?"
				+ "&jsonpCallback=MusicJsonCallback" + "&format=json&inCharset=utf8" + "&outCharset=utf-8&notice=0"
				+ "&platform=yqq&needNewCode=0" + "&cid=205361747" + "&callback=MusicJson"
				+ "&songmid=%s&filename=C400%s.m4a&guid=%s";
		//防止没有歌曲就去爬，防止null
		if(musicMap.size()<1) {
			return;
		}
		
		for (String mid : musicMap.keySet()) {
			String guid = getGuid();
			String keyurl = String.format(vkurl, mid, mid, guid);
			String vkeyjson = null;
			try {
				vkeyjson = AuthUtil.doGetMusic(keyurl);
			} catch (IOException e) {
				e.printStackTrace();
			}
			//自防万一找不到数据
			if(vkeyjson == null) {
				musicMap.remove(mid);
				continue;
			}
			
			vkeyjson = vkeyjson.replace("MusicJson(", "");
			vkeyjson = vkeyjson.substring(0, vkeyjson.length() - 1);
			JSONObject keyy = JSON.parseObject(vkeyjson);
			
			JSONArray keylist = keyy.getJSONObject("data").getJSONArray("items");

			JSONObject d = keylist.getJSONObject(0);

			if(d.getString("vkey") == null || d.getString("vkey") == "") {
				musicMap.remove(mid);
				continue;
			}
			String sonUrl = "http://dl.stream.qqmusic.qq.com/" + d.getString("filename") + "?" + "vkey="
					+ d.getString("vkey") + "&guid=" + guid + "&uin=0" + "&fromtag=66";
			//获取img
			String imgUrl = "https://y.qq.com/n/yqq/song/"+mid+".html";
			String purl = this.getImg(imgUrl);
			//防止出现空连接
			if(purl=="" || purl == null) {
				musicMap.remove(mid);
				continue;
			}
			
			musicMap.get(mid).setMurl(sonUrl);
			musicMap.get(mid).setPurl(purl);
			
		}
	}

	// 获取guid
	private String getGuid() {
		int a = (int) (Math.round(2147483647 * Math.random()) * System.currentTimeMillis() % 1e10);
		String guid = a + "";
		guid = guid.replace("-", "");
		return guid;
	}

	// 根据url获取歌曲的图片
	private String getImg(String url) {
		try {
			Document doc = Jsoup.connect(url).timeout(5000).get();
			// 获取图片
			Elements ele = doc.select("img[class=data__photo]");
			for (Element e : ele) {
				return "https:" + e.attr("src");
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return "";
	}
	
	public static String getlyric(String url) {
		String myurl = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?"
				+ "callback=MusicJsonCallback_lrc"
				+ "&pcachetime=1523930443829"
				+ "&songmid=%s"
				+ "&g_tk=5381&jsonpCallback=MusicJsonCallback_lrc"
				+ "&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0";
		
		String lrcurl = String.format(myurl, url);
		String str = "";
		try {
			String result = AuthUtil.doGetMusicLrc(lrcurl);
			result = result.replace("MusicJsonCallback_lrc(", "");
			result = result.substring(0, result.length()-1);
			JSONObject jo = JSON.parseObject(result);
			String lrc = jo.getString("lyric");
			if(lrc!=null && lrc.length()>10) {
				str = new String(Base64.getDecoder().decode(lrc),"UTF-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	public void getMlyric() {
		String url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?"
				+ "callback=MusicJsonCallback_lrc"
				+ "&pcachetime=1523930443829"
				+ "&songmid=%s"
				+ "&g_tk=5381&jsonpCallback=MusicJsonCallback_lrc"
				+ "&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0";
		
		for(String key : musicMap.keySet()) {
			String lrcurl = String.format(url, key);
			
			try {
				String result = AuthUtil.doGetMusicLrc(lrcurl);
				result = result.replace("MusicJsonCallback_lrc(", "");
				result = result.substring(0, result.length()-1);
				JSONObject jo = JSON.parseObject(result);
				String lrc = jo.getString("lyric");
				if(lrc!=null && lrc.length()>10) {
					musicMap.get(key).setLyric(new String(Base64.getDecoder().decode(lrc),"UTF-8"));
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
